package com.schoolvisitors.utils;

import java.util.Base64;
import java.util.regex.Pattern;

public class ImageValidator {

    // 支持的图片 mime 类型
    private static final Pattern IMAGE_TYPE_PATTERN = Pattern.compile("^data:image/(png|jpeg|jpg);base64,.*");

    /**
     * 校验并返回图片字节
     */
    public static byte[] validateAndDecodeBase64Image(String base64) {
        if (base64 == null || !IMAGE_TYPE_PATTERN.matcher(base64).matches()) {
            throw new IllegalArgumentException("图片格式错误，仅支持 PNG、JPG、JPEG");
        }

        // 去掉前缀
        String pureBase64 = base64.substring(base64.indexOf(",") + 1);

        byte[] decoded;
        try {
            decoded = Base64.getDecoder().decode(pureBase64);
        } catch (IllegalArgumentException e) {
            throw new IllegalArgumentException("Base64解码失败");
        }

        // 校验真实字节大小
        if (decoded.length > 2 * 1024 * 1024) {
            throw new IllegalArgumentException("图片大小不能超过2MB");
        }

        return decoded;
    }
}
